import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { RestService } from '../../services/rest.service';
import { TranslateService } from '@ngx-translate/core';

import * as _ from 'lodash';

@Component({
  selector: 'app-bhhist-dialog',
  templateUrl: './bhhist-dialog.component.html',
  styleUrls: ['./bhhist-dialog.component.css']
})
export class BhhistDialogComponent implements OnInit {
  person: any;
  options: any;

  bChartOptions;
  bEchartsInstance;
  bTitle;

  hChartOptions;
  hEchartsInstance;
  hTitle;

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<BhhistDialogComponent>,
              private translate: TranslateService,
              private rest: RestService,
              private dialog: MatDialog) {
    this.person = dialogData.person;
    this.bTitle = this.translate.get('breathe')['value'];
    this.hTitle = this.translate.get('heart')['value'];
  }

  getTitle() {
    return this.translate.get('hist24hours')['value'] + ' - ' + this.person.personName;
  }

  initChart() {
    this.bChartOptions = _.cloneDeep(this.options);
    this.bChartOptions.title.text = this.bTitle;
    this.bChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.breatheUp},
      {name: 'lower', yAxis: this.person.breatheLow},
    ];

    this.hChartOptions = _.cloneDeep(this.options);
    this.hChartOptions.title.text = this.hTitle;
    this.hChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];
  }

  onBChartInit(ec) {
    this.bEchartsInstance = ec;
    ec.setOption(this.bChartOptions);
  }

  onHChartInit(ec) {
    this.hEchartsInstance = ec;
    ec.setOption(this.hChartOptions);
  }

  buildEmptyData(startTime, endTime) {
    const data = [[startTime * 1000, ''], [endTime * 1000, '']];
    return data;
  }

  initData() {
    const endTime = new Date().getTime() / 1000;
    const startTime = endTime - 24 * 60 * 60;
    const step = 30;
    this.rest.getWithParams('api/v1/query_range', {
      query: 'breathe{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.bChartOptions.title.text = this.bTitle;
          this.bChartOptions.title.textStyle.color = 'darkblue';
          this.bChartOptions.series[0].data = this.buildEmptyData(startTime, endTime);
          this.bEchartsInstance.setOption(this.bChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.bChartOptions.series[0].data = data;
        this.bEchartsInstance.setOption(this.bChartOptions);
      }
    });

    this.rest.getWithParams('api/v1/query_range', {
      query: 'heart{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.hChartOptions.title.text = this.hTitle;
          this.hChartOptions.title.textStyle.color = 'darkblue';
          this.hChartOptions.series[0].data = this.buildEmptyData(startTime, endTime);
          this.hEchartsInstance.setOption(this.hChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.hChartOptions.series[0].data = data;
        this.hEchartsInstance.setOption(this.hChartOptions);
      }
    });
  }

  ngOnInit() {
    this.options = {
      title: {
        text: '',
        subtext: this.translate.get('heartUnit')['value'],
        subtextStyle: {color: 'black'},
        x: 'left',
        y: 'top',
        textStyle: {
          color: 'darkblue'
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1] + ' ' + this.translate.get('heartUnit')['value'];
        }
      },
      grid: {
        x: '50',
        y: '10',
        x2: '30',
        y2: '0',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: true
        }
      },
      yAxis: {
        type : 'value',
        boundaryGap: false,
        splitLine: {
          show: true
        }
      },
      series: [{
        type: 'line',
        showSymbol: false,
        markLine: {
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dashed',
                color: 'darkred'
              }
            }
          },
          data: []
        },
        data: []
      }]
    };

    this.initChart();
    this.initData();
  }
}
